﻿@page "/login"
@rendermode InteractiveServer
@using BlazorAuth.App.Components.Layout
@using BlazorAuth.App.Infrastructures
@using BlazorAuth.App.Models
@using Microsoft.AspNetCore.Components.Authorization
@using System.Text.Json
@layout EmptyLayout
@inject IHttpClientFactory httpClientFactory
@inject NavigationManager Navigation
@inject AuthenticationStateProvider AuthStateProvider

<div class="p-5">
    <EditForm Model="loginModel" FormName="login" OnValidSubmit="HandleLogin">
        <DataAnnotationsValidator />
        <div class="form-group">
            <label for="username">Username</label>
            <InputText id="username" class="form-control" @bind-Value="loginModel.UserName" />
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <InputText id="password" class="form-control" type="password" @bind-Value="loginModel.Password" />
        </div>
        <button type="submit" class="btn btn-primary mt-3">Login</button>
    </EditForm>
</div>

@code {
    private LoginModel loginModel = new LoginModel();

    public async Task HandleLogin()
    {
        var httpClient = httpClientFactory.CreateClient();

        var jsonContent = JsonSerializer.Serialize(loginModel);
        var stringContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
        var httpResponse = await httpClient.PostAsync("https://localhost:7088/api/auth/login", stringContent);
        if (httpResponse.IsSuccessStatusCode)
        {
            var responseContent = await httpResponse.Content.ReadAsStringAsync();
            var loginResponseModel = JsonSerializer.Deserialize<LoginResponseModel>(responseContent, new JsonSerializerOptions()
                {
                    PropertyNameCaseInsensitive = true
                });
            if (loginResponseModel != null && loginResponseModel.Token != null)
            {
                await ((CustomAuthStateProvider)AuthStateProvider).MarkUserAsAuthenticated(loginResponseModel.Token);
                Navigation.NavigateTo("/");
            }
        }
    }
}